package com.lys.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lys.oss.service.OssService;
import com.lys.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Lyyyys
 * @version 1.0
 * @date 2021/3/30 15:07
 */
@Service
public class OssServiceImpl implements OssService{
    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
           //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);

            //上传文件流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();

            //1在文件名称里面添加随机唯一的值
            //asd-123-asd
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid + fileName;

            //2 把文件按照日期进行分类
            //2021/3/30//1.jpg，获取当前日期
            String dataPath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            fileName = dataPath + "/" + fileName;

            //调用oss方法实现上传
            //第一个参数 Bucket名称
            //第二个参数 上传到oss文件路径和文件名称
            //打三个参数 上传文件输入流
            ossClient.putObject(bucketName,fileName,inputStream);

            //关闭OSSClient
            ossClient.shutdown();

            //把上传之后的文件路径返回
            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;

            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
